<template>
    <div class="app-container">
        <div>
            <el-form :model="addInfo" :inline="true" class="w-full" :label-width="language == 'en' ? '150' : '120'">
                <div class="mt-2">
                    <el-form-item :label="$t('goods.groupM.name') + ':'" prop="gm_name" class="w-1/2">
                        <el-input v-model="addInfo.gm_name" :placeholder="$t('message.pleaseEnter')" />
                    </el-form-item>
                    <el-form-item :label="$t('goods.groupM.pic') + ':'" prop="gm_pic" class="w-1/2">
                        <el-input v-model="addInfo.gm_pic" :placeholder="$t('message.pleaseEnter')" readonly>
                            <template #append>
                                <Upload :list="{ 'data': 'goods', 'list': false }" :type="1" :uptype="2"
                                    @exposeData="expose" />
                            </template>
                            <template #suffix>
                                <el-icon class="ml-2 cursor-pointer" size="20" @click="urlimg(addInfo.gm_pic)">
                                    <Picture />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item :label="$t('date.effectiveDate') + ':'" prop="time" class="w-1/2">
                        <el-date-picker type="daterange" :range-separator="$t('public.to')"
                            :start-placeholder="$t('date.startDate')" v-model="data.time"
                            :end-placeholder="$t('date.endDate')" value-format="YYYY-MM-DD" style="width: 100%;" />
                    </el-form-item>
                    <el-form-item :label="$t('goods.groupM.desc') + ':'" prop="gm_desc" class="w-1/2">
                        <el-input v-model="addInfo.gm_desc" autosize type="textarea"
                            :placeholder="$t('message.pleaseEnter')" />
                    </el-form-item>
                    <el-form-item :label="$t('machine.marketing.Applicable') + ':'" prop="grouping" class="w-1/2">
                        <el-select v-model="data.macping" :placeholder="$t('message.pleaseSelectMachine')" clearable
                            filterable @change="getmping($event, 2)">
                            <el-option v-for="item in data.maclist" :key="item.m_id"
                                :label="item.m_id + '-' + item.machine_id + '-' + item.machine_name"
                                :value="item.machine_id" />
                        </el-select>

                        <div class="w-full dashed mt-2 p-2" v-if="data.grouping.length != 0">
                            <el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
                                class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
                                @close="handleClose(key, item)">
                                {{ item.m_id + ' - ' }}{{ item.machine_id || '' }}{{ item.mg_name || ' - ' +
                                    item.machine_name }}
                            </el-tag>
                        </div>

                    </el-form-item>
                </div>
            </el-form>
        </div>
        <!--  -->
        <div>
            <div class="w-full flex flex-wrap p-4">
                <div class="w-6/12">
                    <el-button type="primary" size="large" @click="cusAddGoods"
                        :icon="Plus">{{ $t('goods.groupM.customize') }}</el-button>
                </div>
            </div>
            <div class="w-full p-4 pt-0">
                <el-table :data="addInfo.gList" style="width: 100%" border
                    :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
                    <el-table-column prop="g_name" :label="$t('machine.goods.name')" :width="!isEdit ? '' : '160'">
                        <template #default="scope">
                            <el-select v-model="scope.row.g_id" :placeholder="$t('message.pleaseSelect')" clearable
                                filterable @change="changeGoods(scope.row, scope.$index)">
                                <el-option v-for="(item, index) in goodsList" :key="item.g_id"
                                    :label="item.g_id + '-' + item.g_name" :value="item.g_id" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="g_type" :label="$t('machine.goods.type')">
                        <template #default="scope" v-if="!isEdit">
                            {{ scope.row.typeRow == 1 ? $t('goods.groupM.normalGood') : scope.row.typeRow == 2 ?
                                $t('goods.groupM.hotelGood') : scope.row.typeRow ==
                                    3
                                    ? $t('goods.groupM.ticket') : '' }}
                        </template>
                        <template #default="scope" v-else>
                            <span v-if="scope.row.typeRow"> {{ scope.row.typeRow == 1 ? $t('goods.groupM.normalGood') :
                                scope.row.typeRow == 2
                                    ?
                                    $t('goods.groupM.hotelGood') : scope.row.typeRow == 3 ? $t('goods.groupM.ticket') : ''
                                }}</span>
                            <span v-else>{{ setType(scope.row) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pic" :label="$t('machine.goods.pic')" width="125">
                        <template #default="scope">
                            <img class="w-24 h-24 inline-block" :src="scope.row.pic" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="sku" label="SKU" width="120" />

                    <el-table-column v-if="isEdit" prop="cost_price" :label="$t('machine.goods.costPrice')" />
                    <el-table-column v-if="isEdit" prop="market_price" :label="$t('machine.goods.marketValue')" />

                    <el-table-column prop="selling_price" :label="$t('machine.goods.sellingPrice')"
                        :width="!isEdit ? '' : '175'">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.selling_price" controls-position="right">
                                <template #decrease-icon>
                                    <el-icon>
                                        <Minus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="rise_fall_ratio" :label="$t('goods.groupM.ratio') + '(%)'"
                        :width="!isEdit ? '' : '175'">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.rise_fall_ratio" controls-position="right">
                                <template #decrease-icon>
                                    <el-icon>
                                        <Minus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="buy_lower" :label="$t('goods.groupM.lower')" width="175">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.buy_lower" controls-position="right" :min="1">
                                <template #decrease-icon>
                                    <el-icon>
                                        <Minus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="buy_upper" :label="$t('goods.groupM.upper')" width="175">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.buy_upper" controls-position="right" :min="0">
                                <template #decrease-icon>
                                    <el-icon>
                                        <Minus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="isEdit" prop="performance" :label="$t('goods.groupM.param')">
                        <template #default="scope">
                            <span v-if="!scope.row.performance">{{ $t('goods.groupM.not') }}</span>
                            <span v-else class="text-[#409EFF] cursor-pointer" @click="toMroe(scope.row)">{{
                                $t('public.details') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" :label="$t('public.operate')">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click.prevent="deleteRow(scope.$index, scope.row)">
                                {{ $t('public.del') }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="w-full text-center mt-6">
            <div class="inline-block">
                <el-button type="primary" @click="submit" v-prmis="'machine_group_mg_getList'">{{
                    $t('public.save')}}</el-button>
                <el-button @click="cancell">{{ $t('public.cancel') }}</el-button>
            </div>
        </div>

        <!-- 图片展示 -->
        <el-dialog v-model="data.demonstrate" center width="30%">
            <div class="flex justify-center">
                <el-image class="max-w-80" :src="addInfo.gm_pic" fit="fill" />
            </div>
        </el-dialog>
        <!-- 性能参数 -->
        <el-dialog v-model="isPerformance" :title="$t('goods.groupM.param')" center width="60%" destroy-on-close>
            <el-table :data="performanceList" :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }" class="w-full" border>
                <el-table-column prop="name" :label="$t('goods.groupM.paramName')" />
                <el-table-column prop="lang" :label="$t('public.lang')" />
            </el-table>
        </el-dialog>
    </div>


</template>
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t, locale } = useI18n()
import { Plus } from '@element-plus/icons-vue'
import Upload from '@/components/Upload/index.vue';
import { getmultipleAdd, getmultipleFind, getmultipleUpdate } from '@/api/goods-groupM';
import { getmachineList } from '@/api/machine';
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';
import { getgoodsList } from '@/api/goods'
import getPlevel from '@/utils/level'
let language = ref()
onMounted(() => {
    language.value = locale.value
})
const route = useRoute()
const router = useRouter()
import { onMounted } from 'vue';
let isPerformance = ref(false)
const num = ref(0)
let goodsList = ref([])
let data = reactive({
    demonstrate: false,
    mtloading: false, // 加载状态
    grouping: [],
    macping: '',
    maclist: [],
    macgrouping: [],
    time: []
})
let addInfo = ref({
    gm_name: '',
    gm_pic: '',
    gm_desc: '',
    start_time: 0,
    end_time: 0,
    gList: [{
        gm_id: '',
        g_id: '',
        sku: '',
        selling_price: '',
        rise_fall_ratio: 0,
    }],
    mList: []
})
let performanceList = ref([])
let delMlist = ref([])
let delGlist = ref([])
const now = new Date()
let toMroe = (row: any) => {
    performanceList.value = JSON.parse(row.performance)
    isPerformance.value = true
}
let changeGoods = (row: any, index: number) => {
    for (let item of goodsList.value) {
        if (item.g_id == row.g_id) {
            row.typeRow = item.g_type
            row.sku = item.sku
            row.selling_price = item.retail_price
            row.pic = item.pic
            row.cost_price = item.cost_price
            row.market_price = item.market_price
        }
    }
}
let setType = (row: any) => {
    if (row.g_type == 1) {
        row.g_typeCn = $t('goods.groupM.normalGood')
    }
    if (row.g_type == 2) {
        row.g_typeCn = $t('goods.groupM.hotelGood')
    }
    if (row.g_type == 3) {
        row.g_typeCn =  $t('goods.groupM.ticket')
    }
    return row.g_typeCn
}
let isEdit = computed(() => {
    return route.query.id
})
onMounted(() => {
    if (route.query.id) {
        getmultipleFind({ gm_id: Number(route.query.id) }).then(res => {
            if (res.state == 200) {
                data.grouping = res.data.mList
                let start_time = getPlevel.gettime(res.data.start_time, 3)
                let end_time = getPlevel.gettime(res.data.end_time, 3)
                data.time = [start_time, end_time]
                for (let key in addInfo.value) {
                    addInfo.value[key] = res.data[key]
                }
            }
        })
    }
})
// 删除选中的设备分组/设备
let handleClose = (e: any, row: any) => {
    delMlist.value.push(row.gmm_id)
    data.grouping.splice(e, 1)
}
// 选中分组/设备
let getmping = (e: any, k: any) => {
    let obj = {
        m_id: "",
        machine_id: "",
        machine_name: ""
    }
    // 设备
    data.maclist.map((item) => {
        if (item.machine_id === e) {
            obj.m_id = item.m_id
            obj.machine_id = item.machine_id
            obj.machine_name = item.machine_name
        }
    })
    if (route.query.id) {
        obj.gm_id = route.query.id
    }
    data.grouping.push(obj)
    data.macping = ''
}
let geturlinfo = async () => {
    // 获取设备信息
    await getmachineList({}).then(res => {
        if (res.state == 200) {
            data.maclist = res.data
        }
    })
}
geturlinfo()
// 保存按钮
let submit = () => {
    data.mtloading = true
    addInfo.value.mList = data.grouping
    addInfo.value.start_time = new Date(data.time[0]).getTime() / 1000
    addInfo.value.end_time = new Date(data.time[1]).getTime() / 1000
    addInfo.value.gList = addInfo.value.gList
    if (route.query.id) {
        if (delMlist.value) {
            addInfo.value.delM = delMlist.value.join(',')
        }
        if (delGlist.value) {
            addInfo.value.delG = delGlist.value.join(',')
        }
        addInfo.value.gm_id = Number(route.query.id)
        addInfo.value.gList.forEach(item => {
            item.gm_id = route?.query.id
        })
        getmultipleUpdate(addInfo.value).then(res => {
            data.mtloading = false
            if (res.state == 200) {
                ElMessage({
                    message: $t('message.modifySuccess'),
                    type: 'success'
                })
                router.back()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    } else {
        addInfo.value.gList.forEach(items => {
            for (let item of goodsList.value) {
                if (items.g_id == item.g_id) {
                    items.gm_name = item.g_name
                }
            }
        })

        getmultipleAdd(addInfo.value).then(res => {
            data.mtloading = false
            if (res.state == 200) {
                ElMessage({
                    message: $t('message.addSuccess'),
                    type: 'success'
                })
                router.back()
                return
            }
            ElMessage({
                message: $t('message.networkFailed'),
                type: 'error'
            })
        })
    }

}
// 取消按钮
let cancell = () => {
    for (let key in addInfo.value) {
        addInfo.value[key] = ''
    }
    router.back()
}
// 上传返回
let expose = (e: any) => {
    if (e.status == 200) {
        addInfo.value.gm_pic = e.file.response.data
    } else {
        addInfo.value.gm_pic = ''
    }
}
// 查看图片
let urlimg = (e: any) => {
    if (e == '') {
        return;
    }
    data.demonstrate = true;
}
let cusAddGoods = (e: any) => {
    now.setDate(now.getDate() + 1)
    addInfo.value.gList.push({
        g_id: '',
        sku: '',
        selling_price: '',
        rise_fall_ratio: 0,
    })
}
const deleteRow = (index: number, row: any) => {
    delGlist.value.push(row.gmg_id)
    addInfo.value.gList.splice(index, 1)
}
let getList = () => {
    getgoodsList({}).then(res => {
        if (res.state == 200) {
            goodsList.value = res.data
        }
    })
}
getList()
</script>
<style type="text/css">
.el-textarea__inner {
    height: 80px !important;
}

.dashed {
    border: 2px dashed var(--el-border-color);
}
</style>